package exemplo.database;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import exemplo.model.Login;


public class LoginDAO extends DataBaseConnection{
	
	public LoginDAO() throws SQLException, ClassNotFoundException {
		super();
	}
	
	public boolean validateUser(String username, String password) throws SQLException, ClassNotFoundException {
		PreparedStatement ps = getPreparedStatement("SELECT * FROM login WHERE username = ? AND password = ?;");
		ps.setString(1, username);
		ps.setString(2, password);
		ResultSet rs = ps.executeQuery();
		boolean b = rs.next();
		rs.close();
		ps.close();
		return b;
	}
	
	public Login getById(int code) throws SQLException, ClassNotFoundException {
		PreparedStatement ps = getPreparedStatement("SELECT * FROM login WHERE code = ?;");
		ps.setInt(1, code);
		ResultSet rs = ps.executeQuery();
		Login login = null;
		while (rs.next()) {
			login = new Login();
			populateLogin(login, rs);
		}
		rs.close();
		ps.close();
		return login;
	}
	
	public List<Login> getUsers() throws SQLException, ClassNotFoundException {
		List<Login> list = new LinkedList<Login>();
		ResultSet rs = getStatement().executeQuery("SELECT * FROM login;");
		while (rs.next()) {
			Login login = new Login();
			populateLogin(login, rs);
			list.add(login);
		}
		rs.close();
		return list;
	}
	
	private void populateLogin(Login login, ResultSet rs) throws SQLException {
		login.setCode(rs.getInt("code"));
		login.setName(rs.getString("name"));
		login.setUsername(rs.getString("username"));
		login.setPassword(rs.getString("password"));
	}

}
